package com.neiquan.backstage.meeting_order.web.action;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.neiquan.backstage.common.util.BackendErrorCode;
import com.neiquan.backstage.common.util.CommonResp;
import com.neiquan.backstage.common.util.ExtraSpringHibernateTemplate;
import com.neiquan.backstage.common.util.Paging;
import com.neiquan.backstage.common.util.Sessions;
import com.neiquan.backstage.meeting_order.MeetingOrderService;
import com.neiquan.backstage.meeting_room.MeetingRoomService;
import com.neiquan.backstage.pub.bsc.dao.po.AdminUser;
import com.neiquan.backstage.pub.bsc.dao.po.MeetingOrder;
import com.neiquan.backstage.resourec_manage.EntrepreneurService;

@Controller
@RequestMapping(value = "meetingOrderAction", produces = { "text/json;charset=UTF-8" })
public class MeetingOrderAction {
	private static Class<?> poc = MeetingOrder.class;
	@Autowired
	private ExtraSpringHibernateTemplate extraSpringHibernateTemplate;
	@Autowired
	private MeetingOrderService meetingOrderService;
	@Autowired
	private EntrepreneurService entrepreneurService;
	@Autowired
	private MeetingRoomService meetingRoomService;
	
	@ResponseBody
	@RequestMapping("list")
	public String list(int pageIndex, int pageSize, HttpSession session) throws ParseException {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		Date date = new Date();
		long currentTimeMillis = System.currentTimeMillis();
		date.setTime(currentTimeMillis);
		SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
		String format = simple.format(date);
		Date parse = simple.parse(format);
		Calendar cal = Calendar.getInstance();
		cal.setTime(parse);
		long timeInMillis = cal.getTimeInMillis();
		List<MeetingOrder> listM = (List<MeetingOrder>) extraSpringHibernateTemplate.getHibernateTemplate()
				.find("From MeetingOrder where memberId=? and dtCreat>?", memberId,timeInMillis);
		if(listM.size()<=0){
			return CommonResp.buildSuccessResp().toJsonString();
		}
		List<Object> ListM = new ArrayList<>();
		for(MeetingOrder mo:listM){
			String time="";
			Map<String, Object> mapM = new HashMap<>();
			mapM.put("meetingRoomName", mo.getMeetingRoomName());
			mapM.put("status", mo.getStatus());
			mapM.put("entrepreneurName", mo.getEntrepreneurName());
			mapM.put("name", mo.getName());
			mapM.put("phone", mo.getPhone());
			mapM.put("meetingOrderId", mo.getMeetingOrderId());
			String times = mo.getTimes();
			if(times!=null&&!times.equals("")){
				String[] split = times.split(",");
				String[] split3 = split[0].split("-");
				if(split3.length>3){
					time =split3[0]+"-"+split3[1]+"-"+split3[2]+" ";
					int[] array=new int[split.length];
					for(int i=0;i<split.length;i++){
						String[] split2 = split[i].split("-");
						String b=split2[3];
						array[i]=Integer.parseInt(b);
					}
					Arrays.sort(array);
					int mina=array[0];
					int maxa=array[split.length-1];
					time+=mina+"--"+maxa;
					mapM.put("time", time);
				}
			}
			ListM.add(mapM);
		}
		return CommonResp.buildSuccessResp(ListM).toJsonString();
	}
	
	@ResponseBody
	@RequestMapping("findByMRNameAll")
	public String findByMRNameAll(String meetingRoomName,HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<MeetingOrder> list=(List<MeetingOrder>) extraSpringHibernateTemplate.getHibernateTemplate().find("From MeetingOrder where memberId=? and meetingRoomName=?", memberId,meetingRoomName);
		return CommonResp.buildSuccessResp(list).toJsonString();
	}

	@ResponseBody
	@RequestMapping("findByAddressAll")
	public String findByAddressAll(Integer meetingRoomId,HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		List<MeetingOrder> list=(List<MeetingOrder>) extraSpringHibernateTemplate.getHibernateTemplate().find("From MeetingOrder where memberId=? and meetingRoomId=?", memberId,meetingRoomId);
		return CommonResp.buildSuccessResp(list).toJsonString();
	}
	@ResponseBody
	@RequestMapping("findAll")
	public String findAll(HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Criterion criterion = Restrictions.eq("memberId", loginedUser.getMemberId());
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("meetingOrderId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}
	@ResponseBody
	@RequestMapping(value = "queryDetail")
	public String queryDetail(Integer id) {
		return CommonResp.buildSuccessResp(meetingOrderService.queryById(id)).toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "remove")
	public String remove(Integer id) {
		MeetingOrder toDelete = meetingOrderService.queryById(id);
		if (toDelete == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		extraSpringHibernateTemplate.getHibernateTemplate().delete(toDelete);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "pass")
	public String pass(Integer id) {
		MeetingOrder toUpdate = meetingOrderService.queryById(id);
		if (toUpdate == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		if (toUpdate.getStatus() != MeetingOrder.status_wait) {
			return CommonResp.buildErrorResp(BackendErrorCode.status_error).toJsonString();
		}
		toUpdate.setStatus(MeetingOrder.status_pass);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "reject")
	public String reject(Integer id) {
		MeetingOrder toUpdate = meetingOrderService.queryById(id);
		if (toUpdate == null) {
			return CommonResp.buildErrorResp(BackendErrorCode.not_exist).toJsonString();
		}
		if (toUpdate.getStatus() != MeetingOrder.status_wait) {
			return CommonResp.buildErrorResp(BackendErrorCode.status_error).toJsonString();
		}
		toUpdate.setStatus(MeetingOrder.status_reject);
		extraSpringHibernateTemplate.getHibernateTemplate().update(toUpdate);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	@ResponseBody
	@RequestMapping(value = "search")
	public String search(String name, String entrepreneurName, HttpSession session) {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		List<Criterion> criterions = new ArrayList<>();
		criterions.add(Restrictions.eq("memberId", loginedUser.getMemberId()));
		if (StringUtils.isNoneBlank(name)) {
			criterions.add(Restrictions.like("name", "%" + name + "%"));
		}
		if (StringUtils.isNoneBlank(entrepreneurName)) {
			criterions.add(Restrictions.like("entrepreneurName", "%" + entrepreneurName + "%"));
		}
		Criterion criterion = Restrictions.and(criterions.toArray(new Criterion[] {}));
		DetachedCriteria queryListCriteria = ExtraSpringHibernateTemplate.C.build(poc, Order.desc("meetingOrderId"), criterion);
		DetachedCriteria queryCountCriteria = ExtraSpringHibernateTemplate.C.buildRowCount(poc, criterion);
		Paging<?> paging = extraSpringHibernateTemplate.findPageByCriteria(queryListCriteria, queryCountCriteria, 0, Integer.MAX_VALUE);
		return CommonResp.buildSuccessResp(paging).toJsonString();
	}
/**
 * 时间存入方法
 * @param meetingRoomId
 * @param entrepreneurId
 * @param name
 * @param phone
 * @param orderTimes
 * @param session
 * @return
 * @throws ParseException
 */
	@ResponseBody
	@RequestMapping(value = "add")
	public String add(Integer meetingRoomId,Integer entrepreneurId, String name, String phone, @RequestParam("orderTimes[]")String[] orderTimes, HttpSession session) throws ParseException {
		AdminUser loginedUser = (AdminUser) Sessions.getLoginedUser(session);
		Integer memberId = loginedUser.getMemberId();
		MeetingOrder toSave = new MeetingOrder();
		toSave.setMemberId(memberId);
		String times="";
		for(String str:orderTimes){
			toSave.setStatus(MeetingOrder.status_wait);
			String[] strs=str.split(",");
			String str1=strs[0];
			Integer h=Integer.parseInt(strs[1]);
			String st=str1.substring(0, 15).trim();
			SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy",Locale.US);
			Date d = sdf.parse(st);
			Calendar instance = Calendar.getInstance();
			instance.setTime(d);
			instance.add(Calendar.MONTH, +1);
			instance.add(Calendar.DAY_OF_MONTH, +1);
			int i = instance.get(Calendar.YEAR);
			int j = instance.get(Calendar.MONTH);
			int k = instance.get(Calendar.DAY_OF_MONTH);
			String strTime=i+"-"+j+"-"+k+"-"+h;
			times+=strTime+",";
		}
		times=times.substring(0, times.length()-1);
		toSave.setTimes(times);
		toSave.setEntrepreneurId(entrepreneurId);
		toSave.setApplyType(MeetingOrder.apply_meeting);
		toSave.setEntrepreneurName(entrepreneurService.queryById(entrepreneurId).getName());
		toSave.setName(name);
		toSave.setDtCreat(System.currentTimeMillis());
		toSave.setMeetingRoomId(meetingRoomId);
		toSave.setMeetingRoomName(meetingRoomService.queryById(meetingRoomId).getName());
		toSave.setPhone(phone);
		extraSpringHibernateTemplate.getHibernateTemplate().save(toSave);
		return CommonResp.buildSuccessResp().toJsonString();
	}

	
}
